package com.rhok.wthru_client;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.rhok.utils.LocationUtils;
import com.rhok.utils.LocationUtils.MyLocationListener;
import com.rhok.wthru_client.servermsgs.ServerMessageRequestLocation;

public class MainActivity extends Activity {

	protected List<BasicContactInfo> m_contacts = new ArrayList<BasicContactInfo>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		((Button) this.findViewById(R.id.my_location_button))
				.setOnClickListener(myLocationOnClickListener);
		((Button) findViewById(R.id.pick_person))
				.setOnClickListener(getContentClickListener);
		((Button) findViewById(R.id.send)).setOnClickListener(send);
	}

	protected OnClickListener getContentClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
			startActivityForResult(intent, 1);
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	protected OnClickListener myLocationOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {

			Intent i = new Intent(getApplicationContext(), MyMapActivity.class);
			startActivity(i);
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data != null) {
			Uri uri = data.getData();

			if (uri != null) {
				Cursor c = null;
				try {
					c = getContentResolver()
							.query(uri,
									new String[] {
											ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
											ContactsContract.CommonDataKinds.Phone.NUMBER },
									null, null, null);

					if (c != null && c.moveToFirst()) {
						addContactToList(c.getString(0), c.getString(1));
					}
				} finally {
					if (c != null) {
						c.close();
					}
				}
			}
		}
	}

	public void addContactToList(String name, String number) {
		BasicContactInfo contact = new BasicContactInfo(name, number);
		if (m_contacts.contains(contact)) {
			Toast.makeText(this,
					"Contact: " + name + " - " + number + " is already added",
					Toast.LENGTH_LONG).show();
			return;
		}
		TableLayout tl = (TableLayout) findViewById(R.id.myTableLayout);
		TableRow tr1 = new TableRow(this);
		tr1.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT));
		TextView textview = new TextView(this);
		textview.setText(name);
		textview.setTextSize(18);
		textview.setTextColor(Color.BLUE);
		tr1.addView(textview);
		tl.addView(tr1, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT));

		m_contacts.add(contact);
		Toast.makeText(this, "Added Contact: " + name + " - " + number,
				Toast.LENGTH_LONG).show();
	}

	protected OnClickListener send = new OnClickListener() {

		@Override
		public void onClick(View v) {
			final ServerMessageRequestLocation smrl = new ServerMessageRequestLocation(
					getApplicationContext());
			smrl.setContacts(m_contacts.toArray(new BasicContactInfo[0]));
			// TODO: smrl.setSelfInfo()
			if (((CheckBox) findViewById(R.id.add_mine)).isChecked()) {
				final String sendAlsoMe = " [Sending my location as well]";

				GlobalConfiguration gc = GlobalConfiguration
						.getInstance(getApplicationContext());
				Location location = gc.getLastKnownLocation();
				if (location == null) {

					LocationUtils.waitForLocation(new MyLocationListener() {

						@Override
						public void locationReceived(Location location) {
							setLocation(smrl, location);
							sendMessage(smrl, sendAlsoMe);
						}
					}, getApplicationContext());

				} else {
					setLocation(smrl, location);
					sendMessage(smrl, sendAlsoMe);
				}
			} else {
				
				sendMessage(smrl, "");
			}

		}

		private void setLocation(ServerMessageRequestLocation smrl,
				Location location) {
			GeoPoint gp = LocationUtils.locationToPoint(location);
			smrl.setMyLocation(gp);
		}

		private void sendMessage(ServerMessageRequestLocation smrl,
				String sendAlsoMe) {

			Toast.makeText(
					getApplicationContext(),
					"Sending to " + m_contacts.size() + " contacts. "
							+ sendAlsoMe, Toast.LENGTH_LONG).show();
			smrl.send();
		}

		// TODO: code for receiving name from phone number
		/*
		 * Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
		 * Uri.encode(phoneNumber)); Cursor c = getContentResolver().query(uri,
		 * new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null); if (c !=
		 * null && c.moveToFirst()) { Toast.makeText(getApplicationContext(),
		 * "Yes - "+c.getString(0), Toast.LENGTH_LONG).show(); }
		 */
	};
}
